﻿using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel;
using Alipay.EasySDK.Kernel.Util;
using Alipay.EasySDK.Payment.FaceToFace.Models;
using Alipay.EasySDK.Payment.Page.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace LiveShopvnext.Pay
{
    public class ALiPayAppService : ApplicationService, IALiPayAppService
    {
        private readonly IHttpContextAccessor _contextAccessor;

        public ALiPayAppService(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
        [HttpGet]
        //直接测试用地址,记得改订单信息. https://localhost:44341/api/app/a-li-pay/pay?Subject=test1&outTradeNo=111111111112&totalAmount=500
        public async void Pay(PayDto dto)
        {
            #region 1. 设置参数（全局只需设置一次）
            var config = new Config()
            {
                Protocol = "https",
                GatewayHost = "openapi.alipaydev.com",//"openapi.alipay.com",沙箱
                SignType = "RSA2",
                AppId = "2021000119610553",
                //请填写您的应用私钥
                MerchantPrivateKey = "MIIEowIBAAKCAQEAxO/0Ib7ZkU6jAYff/G4sHlMdE56h0Wlz/x4IjG5/h8vhnVhqo8cp9AMW0VchKGf7cIBYSF341igrRTVEX4H2Th/Hbg8Nh9xuKCS6353dgTaF7NEkw+HFb0fgr+bUnttgr8NYgOOfewozMVTykRlvje/PDuAyWxZeLrE9t6t2qY2Bk18pfF2Lu4Ky75p/4s2bb0UQjrIDe9DtEaMwvk3ds3q/YsNH0cYrzRRkt0ATfdd1GDQLLaOmbLHDF55HNUxT4/MCxLGGzC+hCFAzYYkGoR8M0l5wkkXhO/WHFUlEvlXTcQLoDKlcTqnFvdLAClthoY4nEjqTcWpu3ekOlIWyJQIDAQABAoIBABg2C8RuSx8jFMUmaDIHdWMRAr0bvncZSMpvbcud9g3C0ezfJtUVsiGuk4qO9KOcDPxquu/CpcnmTFOI1ewL9TTrkUAFl7tBL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JGLrvtu4xtZaTtdJCkqFIHckTiN35a1+QntaP3k5QUCN9oBKt",
                //支付宝公钥
                AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxO/0Ib7ZkU6jAYff/G4sHlMdE56h0Wlz/x4IjG5/h8vhnVhqo8cp9AMW0VchKGf7cIBYSF341igrRTVEX4H2Th/Hbg8Nh9xuKCS6353dgTaF7NEkw+HFb0fgr+bUnttgr8NYgOOfewozMVTykRlvje/PDuAyWxZeLrE9t6t2qY2Bk18pfF2Lu4Ky75p/4s2bb0UQjrIDe9DtEaMwvk3ds3q/YsNH0cYrzRRkt0ATfdd1GDQLLaOmbLHDF55HNUxT4/MCxLGGzC+hCFAzYYkGoR8M0l5wkkXhO/WHFUlEvlXTcQLoDKlcTqnFvdLAClthoY4nEjqTcWpu3ekOlIWyJQIDAQAB",
                //异步回调地址
                NotifyUrl = "https://localhost:44322/api/app/a-li-pay/notify-url",
            };
            Factory.SetOptions(config);
            #endregion
            try
            {

                // 2. 发起API调用（以创建当面付收款二维码为例）
                //TODO:实训标题和订单号及金额是从dto中取得
                AlipayTradePagePayResponse response = Factory.Payment.Page().Pay(dto.Subject, dto.outTradeNo, dto.totalAmount, "https://localhost:44322/api/app/a-li-pay/return-url");
                // 3. 处理响应或异常
                if (ResponseChecker.Success(response))
                {
                    //把返回的html直接变成网页显示
                    var data = Encoding.UTF8.GetBytes(response.Body);
                    _contextAccessor.HttpContext.Response.ContentType = "text/html";
                    await _contextAccessor.HttpContext.Response.Body.WriteAsync(data, 0, data.Length);
                }
                else
                {
                    Console.WriteLine("调用失败，原因：" + response.Body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("调用遭遇异常，原因：" + ex.Message);


            }
        }
        //同步回调地址
        [HttpGet]
        public string ReturnUrl(PayReturnDto dto)
        {
            //支付宝提供的验证签名的方法
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters)==true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加返回的支付宝流水订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //if()先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update

                //把库存还原

                return "success";
            }
            return "";
        }
        //异步回调地址
        [HttpGet]
        public string NotifyUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update
                //再循环返回库存
                //update


                return "success";
            }
            return "";
        }
    }
}
